package com.woyou.ui.activity;

import java.io.File;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.citaq.ideliver.R;
import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;
import com.woyou.bean.Info;
import com.woyou.model.ActivitiesModel;
import com.woyou.model.ActivitiesModel_;
import com.woyou.model.FileModel;
import com.woyou.model.FileModel_;
import com.woyou.model.GoodsModel;
import com.woyou.model.GoodsModel_;
import com.woyou.model.OrderModel;
import com.woyou.model.OrderModel_;
import com.woyou.model.PropPanelModel;
import com.woyou.model.PropPanelModel_;
import com.woyou.model.ShoppingCarModel;
import com.woyou.model.ShoppingCarModel_;
import com.woyou.model.ShopsModel;
import com.woyou.model.ShopsModel_;
import com.woyou.model.UserModel;
import com.woyou.model.UserModel_;
import com.woyou.service.NetWorkCenter;
import com.woyou.service.NetWorkCenter_;
import com.woyou.service.ThreadPoolManager;
import com.woyou.service.ThreadPoolManager_;
import com.woyou.service.location.BaiduLocationService;
import com.woyou.service.location.BaiduLocationService_;
import com.woyou.ui.api.IBackEventStrategy;
import com.woyou.ui.view.SuperUI;
import com.woyou.utils.Task;

public abstract class BaseActivity extends Activity implements IBackEventStrategy, SuperUI, OnClickListener {

	ThreadPoolManager mThreadPoolManager;

	protected BaiduLocationService mBaiduLocationService;

	protected Context mContext;

	protected ProgressDialog progress;

	@SuppressWarnings("rawtypes")
	protected Info mInfo;

	public static final String INFO_NAME = "info";

	protected Activity mActivity;

	protected NetWorkCenter mNetWorkCenter;
	
	/**所有Model**/
	protected ShopsModel mShopsModel;
	protected ShoppingCarModel mShoppingCarModel;
	protected GoodsModel mGoodsModel;
	protected ActivitiesModel mActivitiesModel;
	protected FileModel mFileModel;
	protected PropPanelModel mPropPanelModel;
	protected OrderModel mOrderModel;
	protected UserModel mUserModel;
	
	/**
	 * 动画
	 */
	private AnimationDrawable animationDrawable;

	/**
	 * 当前最后执行的线程任务,task的ID属性可以用于判断线程启动的先后
	 */
	protected Task lastTask = new Task(0) {

		@Override
		public void run() {

		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mActivity = this;
		mContext = this;
		
		mThreadPoolManager = ThreadPoolManager_.getInstance_(mContext);

		progress = getProgressDialog("正在加载,请稍后...");
		progress.setCancelable(true);
		
		mNetWorkCenter = NetWorkCenter_.getInstance_(mContext.getApplicationContext());
		mBaiduLocationService = BaiduLocationService_.getInstance_(mContext.getApplicationContext());

		/*model实例化*/
		mShopsModel = ShopsModel_.getInstance_(getContext().getApplicationContext());
		mShoppingCarModel = ShoppingCarModel_.getInstance_(getContext().getApplicationContext());
		mGoodsModel = GoodsModel_.getInstance_(getContext().getApplicationContext());
		mActivitiesModel = ActivitiesModel_.getInstance_(getContext().getApplicationContext());
		mFileModel = FileModel_.getInstance_(getContext().getApplicationContext());
		mPropPanelModel = PropPanelModel_.getInstance_(getContext().getApplicationContext());
		mOrderModel = OrderModel_.getInstance_(getContext().getApplicationContext());
		mUserModel = UserModel_.getInstance_(getContext().getApplicationContext());
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	public ProgressDialog getProgressDialog(String msg) {
		ProgressDialog progressDialog = new ProgressDialog(mContext);
		progressDialog.setMessage(msg);
		progressDialog.setCancelable(true);
		return progressDialog;
	}

	/**
	 * 运行在主线程中的Toast
	 */
	public void showToastOnUI(final String msg) {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
			}
		});

	}

	/**
	 * 弹出Toast
	 * 
	 * @param msg
	 */
	public void showToast(String msg) {
		Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
	}

	/**
	 * UI线程执行一个任务
	 * 
	 * @param run
	 */
	public void runOnUI(Runnable run) {
		runOnUiThread(run);
	}

	/**
	 * 子线程执行一个任务
	 * 
	 * @param task
	 */
	public void executeTask(Task task) {
		this.lastTask = task;
		mThreadPoolManager.executeTask(task);
	}

	/**
	 * 
	 * @param run
	 */
	public void executeTask(Runnable run) {
		mThreadPoolManager.executeTask(run);
	}

	/**
	 * 隐藏输入法
	 * 
	 * @param context
	 * @param achor
	 */
	public void hideSoftInput(Context context, View achor) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(achor.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	public void dismissProgressDialog() {
		runOnUI(new Runnable() {

			@Override
			public void run() {
				if (progress != null) {
					progress.dismiss();
				}

			}
		});

	}

	public void showProgressDialog() {
		runOnUI(new Runnable() {

			@Override
			public void run() {
				if (progress == null) {
					progress = new ProgressDialog(mContext);
					progress.setMessage("正在加载,请稍后...");
					progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				}
				progress.setCancelable(true);
				try {
					progress.show();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

	}

	public void showProgressDialog(final String msg, final boolean isCancel) {
		runOnUI(new Runnable() {

			@Override
			public void run() {
				if (progress == null) {
					progress = new ProgressDialog(mContext);
					progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				}
				progress.setMessage(msg);
				progress.setCancelable(isCancel);
				try {
					progress.show();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

	}

	@Override
	public void onDestroy() {
		if (progress != null) {
			progress.dismiss();
		}
		super.onDestroy();
	}

	/**
	 * 是否有数据传递过来
	 * 
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public boolean hasInfo() {
		if(getIntent() != null) {
			mInfo = (Info) getIntent().getSerializableExtra(INFO_NAME);
			if (mInfo != null) {
				return true;
			}
		}
		return false;
	}

	@SuppressWarnings("rawtypes")
	public Info getInfoBean() {
		if (getIntent() == null) {
			return null;
		} else
			return (Info) getIntent().getSerializableExtra(INFO_NAME);
	}

	/**
	 * 打开一个Activity
	 * 
	 * @param clazz
	 * @param info
	 */
	@SuppressWarnings("rawtypes")
	public void openActivity(final Class clazz, final Info info) {
		runOnUI(new Runnable() {

			@Override
			public void run() {
				Intent intent = new Intent();
				intent.setClass(mContext, clazz);
				if (info != null) {
					intent.putExtra(INFO_NAME, info);
				}
				startActivity(intent);
			}
		});

	}

	/**
	 * 打开一个Activity for result
	 * 
	 * @param clazz
	 * @param info
	 */
	@SuppressWarnings("rawtypes")
	public void openActivity4Result(final Class clazz, final Info info, final int requestCode) {
		runOnUI(new Runnable() {

			@Override
			public void run() {
				Intent intent = new Intent();
				intent.setClass(mContext, clazz);
				if (info != null) {
					intent.putExtra(INFO_NAME, info);
				}
				startActivityForResult(intent, requestCode);
			}
		});

	}

	/**
	 * 返回数据到上一个activity
	 * 
	 * @param resultCode
	 * @param data
	 */
	@SuppressWarnings("rawtypes")
	public void closeActivity4Result(int resultCode, Info data) {
		Intent intent = getIntent();
		intent.putExtra(INFO_NAME, data);
		setResult(resultCode, intent);
		finish();
	}

	/**
	 * SingTask 需要重写该方法
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		setIntent(data);
	}
	
	/**
	 * 加载图片
	 * 
	 * @param tuContainer
	 * @param item
	 */
	public void loadIMG(ImageView img, String url) {
		Picasso.with(mContext).load(url).error(R.drawable.error).into(img);
	}

	public void loadIMG(ImageView img, String url, int errorId) {
		if (errorId == 0) {
			Picasso.with(this).load(url).into(img);
		} else {
			Picasso.with(this).load(url).error(errorId).placeholder(errorId).into(img);
		}

	}

	public void loadIMG(ImageView img, String url, int placeholder, int errorId) {
		Picasso.with(mContext).load(url).error(errorId).placeholder(placeholder).into(img);
	}

	/**
	 * 加载图片
	 * 
	 * @param tuContainer
	 * @param item
	 */
	public void loadIMG(ImageView img, File file) {
		Picasso.with(mContext).load(file).error(R.drawable.error).into(img);
	}

	/**
	 * 加载本地图片
	 * 
	 * @param tuContainer
	 * @param item
	 */
	public void loadIMG(ImageView img, int id) {
		Picasso.with(mContext).load(id).into(img);
	}

	/**
	 * 获得配置文件参数
	 * 
	 * @param id
	 * @return
	 */
	public float getDimens(int id) {
		return getResources().getDimension(id);
	}

	/**
	 * 获得配置文件参数
	 * 
	 * @param id
	 * @return
	 */
	public int getDimensPixelSize(int id) {
		return getResources().getDimensionPixelSize(id);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean flag = false;
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // 按下的如果是BACK，同时没有重复
			flag = backOperate();
		}
		if (!flag) {
			return super.onKeyDown(keyCode, event);
		}
		return flag;
	}

	@Override
	public Context getContext() {
		return this;
	}

	@Override
	public OnClickListener getClickListener() {
		return this;
	}

	@Override
	public void onClick(View v) {

	}

	/**
	 * 获取静态地图的url
	 * 
	 * @return
	 */
	public String getStaticMapUrl(String w, String h, String center, String markers, String zoom) {
		// String url =
		// "http://api.map.baidu.com/staticimage?width=300&height=300&center=121.5182420,31.3114690&markers=121.5182420,31.3114690&zoom=18";
		String url = "http://api.map.baidu.com/staticimage?width=%s&height=%s&center=%s&markers=%s&zoom=%s";
		url = String.format(url, w, h, center, markers, zoom);
		return url;
	}

	/**
	 * 显示动画loading
	 */
	public void showLoading(final ImageView iv) {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				iv.setImageResource(R.anim.loading);
				animationDrawable = (AnimationDrawable) iv.getDrawable();
				animationDrawable.start();
			}
		});

	}

	/**
	 * 隐藏动画loading
	 */
	public void hideLoading() {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				if (animationDrawable != null && animationDrawable.isRunning()) {
					animationDrawable.stop();
				}
			}
		});

	}

}
